package rexsee.core.storage;

import java.io.File;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import android.os.Environment;
import android.os.StatFs;

public class RexseeStorage implements JavascriptInterface {

	public static final String INTERFACE_NAME = "Storage";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseeStorage(childBrowser);
	}

	private final Browser mBrowser;

	public RexseeStorage(Browser browser) {
		mBrowser = browser;
	}

	//JavaScript Interface
	public boolean isReady() {
		return (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) ? true : false;
	}
	public String getRoot() {
		return (isReady()) ? "file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/" : "";
	}
	public long getTotalSpace() {
		String status = Environment.getExternalStorageState();
		long totalSpace = 0;
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			try {
				File path = Environment.getExternalStorageDirectory();
				StatFs stat = new StatFs(path.getPath());
				long blockSize = stat.getBlockSize();
				long availableBlocks = stat.getBlockCount();
				totalSpace = availableBlocks * blockSize / 1024;
			} catch (Exception e) {
				return -1;
			}
		} else {
			return -1;
		}
		return totalSpace;
	}
	public long getFreeSpace() {
		String status = Environment.getExternalStorageState();
		long freeSpace = 0;
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			try {
				File path = Environment.getExternalStorageDirectory();
				StatFs stat = new StatFs(path.getPath());
				long blockSize = stat.getBlockSize();
				long availableBlocks = stat.getAvailableBlocks();
				freeSpace = availableBlocks * blockSize / 1024;
			} catch (Exception e) {
				return -1;
			}
		} else {
			return -1;
		}
		return freeSpace;
	}

	public static long getAvailableROMSize() {
		File path = Environment.getDataDirectory();
		StatFs stat = new StatFs(path.getPath());
		long blockSize = stat.getBlockSize();
		long availableBlocks = stat.getAvailableBlocks();
		return blockSize * availableBlocks;
	}

	public static long getTotalROMSize() {
		File path = Environment.getDataDirectory();
		StatFs stat = new StatFs(path.getPath());
		long blockSize = stat.getBlockSize();
		long totalBlocks = stat.getBlockCount();
		return totalBlocks * blockSize;
	}

}
